import { ComponentType } from '@angular/cdk/portal'
import { Injectable } from '@angular/core'
import { MatDialog, MatDialogConfig } from '@angular/material/dialog'

export interface AdDialogConfig<D> extends MatDialogConfig<D> {
  rejectValue?: any[]
}

@Injectable()
export class AdDialog {
  constructor(private dialog: MatDialog) {}
  /**
   * 打开dialog 返回promise
   * @param component 要打开的组件
   * @param adDialogConfig 弹窗配置项
   * @returns
   */
  async open<T, D = any>(
    component: ComponentType<T>,
    adDialogConfig: AdDialogConfig<D> = {}
  ): Promise<any> {
    const { rejectValue = ['', undefined, false], ...config } = adDialogConfig
    const result = await this.dialog.open(component, config).afterClosed().toPromise()
    if (rejectValue.includes(result)) {
      return Promise.reject('dialog close reject')
    }
    return Promise.resolve(result)
  }
}
